<script setup lang='ts'>
import { useUserStore } from '@/stores/useUserStore';
import { findStudentAll, findClassAll, studentHWUpload } from '@/api/hwApi'
import { getInterfilesAll, addInterfiles } from "@/api/interfilesApi"
import { ref, computed } from 'vue';
import { ElLoading, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

defineOptions({
  name: 'VHWList',
})

const { userInfo } = useUserStore()
const router = useRouter()

// 作业列表
const hwStudentList = ref([])
async function fetchHWList() {
  const result = await findStudentAll(userInfo.classId, userInfo.id)
  hwStudentList.value = result.data
}
fetchHWList()


// hwClassList
const hwClassList = ref([])
async function fetchHWClassList() {
  const result = await findClassAll(userInfo.classId)
  hwClassList.value = result.data
}

fetchHWClassList()

// 归档列表
const InterfilesList = ref([])


function fetchInterfilesAll() {
  getInterfilesAll(userInfo.id).then(res => {
    InterfilesList.value = res.data.map((item) => {
      return {
        ...item,
        label: item.nickname,
        value: item.id
      }
    })
  })
}

const dataList = computed(() => {
  const newList = hwStudentList.value.map((item) => {
    const classItem = hwClassList.value.find((classhw) => classhw.id === item.homeWorkId)
    // console.log(item.interfilesId);
    // const interfilesItem = InterfilesList.value.find((interfiles) => interfiles.id === item.interfilesId)
    const interfilesArr = item.interfilesId && item.interfilesId.split(',')
    const interfilesArrayInfo = interfilesArr && interfilesArr.map((interfilesId) => {
      return InterfilesList.value.find((interfiles) => {
        if (interfiles.id === parseInt(interfilesId)) {
          return {
            label: interfiles.nickname,
            value: interfiles.id,
            ...interfiles,
          }
        }
      })
    })
    console.log(interfilesArrayInfo);
    return {
      ...item,
      ...classItem,
      interfilesArrayInfo, // 归档信息
      EditInterfiles: false // 编辑归档
    }
  })

  return newList;
})

fetchInterfilesAll()
const drawer = ref(false)
const direction = ref('rtl')
function handleClose() {
  drawer.value = false
}
const handleOpenDia = (item) => {
  drawer.value = true
}

const inputTag = ref('')
const inputTagVisible = ref(false)
// 处理新建归档
async function handleInputConfirm() {
  const { code, msg } = await addInterfiles(userInfo.id, inputTag.value)
  if (code === 2000) {
    // fetchInterfilesAll()
    inputTagVisible.value = false
    inputTag.value = ''
    ElMessage.success(msg)
  } else {
    ElMessage.error(msg)
  }
}

const fileDom = ref(null)

async function submitUpload(item) {
  const file = fileDom.value[0].files[0];
  const { code, msg } = await studentHWUpload(file, item.stuId, item.classId, item.homeWorkId)
  ElLoading.service({
    lock: true,
    text: '上传中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  if (code === 2000) {
    ElMessage.success(msg)
    fetchHWList()
  } else {
    ElMessage.error(msg)
  }
  ElLoading.service().close()

}

const hasFile = ref(false)
// 选择文件事件
const handleInput = function () {
  hasFile.value = true
}

const handleToDetail = (row) => {
  console.log(row);
  router.push({
    path: `/hw/detail/${row.classId}/${row.homeWorkId}`,
  })
}

</script>

<template>
  <div class='hw-container'>
    <h1>作业列表</h1>
    <ul class="hw-list">
      <li class="hw-item" v-for="hwItem in dataList" :key="hwItem.id">
        <div class="hw-item-title">
          <div>
            <span>【作业名称】：{{ hwItem.nickname }}</span>
            <span>【提交状态】：
              <el-tag v-if="hwItem.state === 0" type="danger">未交</el-tag>
              <el-tag v-else type="success">已交</el-tag>
            </span>
            <span v-if="hwItem.score !== null">【分数】：
              <el-tag size="large" type="success">{{ hwItem.score }}</el-tag>
            </span>
          </div>
          <div>
            <span>【开始时间】：{{ hwItem.startTime }}</span>
            <span>【截止时间】：{{ hwItem.endTime }}</span>
          </div>
          <div v-if="hwItem.interfilesArrayInfo">
            <span>【归档】：</span>
            <!-- <el-tag v-if="hwItem.interfilesArrayInfo" v-for="interfilesItem in hwItem.interfilesArrayInfo"
              :key="interfilesItem.id" type="info">{{
                interfilesItem.nickname }}</el-tag> -->
            <el-select v-model="hwItem.interfilesArrayInfo" multiple filterable allow-create default-first-option
              :reserve-keyword="false" placeholder="Choose tags for your article" style="width: 240px">
              <el-option v-for="item in InterfilesList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>

          </div>
        </div>
        <div class="operator" style="display: flex;">
          <div style="margin-right: 20px;">
            <el-button class="ml-3" type="info" @click="handleToDetail(hwItem)">
              作业详情
            </el-button>
          </div>
          <!-- 上传文件区域 -->
          <div style="display: flex;flex-direction: column;width: 200px;">
            <el-button class="ml-3" :disabled="!hasFile" type="success" @click="submitUpload(hwItem)">
              确认上传
            </el-button>
            <input class="uploader" type="file" ref="fileDom" @input="handleInput" />
          </div>
          <el-button type="info" size="mini" @click="handleOpenDia(hwItem)">归档</el-button>

        </div>
      </li>
    </ul>
    <!-- 归档窗口 -->
    <el-drawer v-model="drawer" title="编辑归档" :direction="direction" :before-close="handleClose">
      <div>归档列表：
        <el-tag size="large" v-for="interfilesItem in InterfilesList" :key="interfilesItem.id" type="info">{{
          interfilesItem.nickname }} + </el-tag>
        <el-input v-if="inputTagVisible" v-model="inputTag" class="w-20" size="small" @keyup.enter="handleInputConfirm"
          @blur="handleInputConfirm" />

        <el-button v-else class="button-new-tag" size="small" @click="inputTagVisible = true">
          + New Tag
        </el-button>
      </div>
      <div>已选归档：
        <el-tag v-for="interfilesItem in InterfilesList" :key="interfilesItem.id" type="info">{{
          interfilesItem.nickname }}</el-tag>

      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang='scss'>
.hw-list {
  .hw-item {
    margin-top: 20px;
    padding: 10px;
    border-bottom: 1px solid #b2b2b2;
    display: flex;
    justify-content: space-between;
    cursor: pointer;

    &:hover {
      background-color: #abcdef;
    }
  }
}
</style>